window.onload = function(){

       $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
       })
       //获取DOM 对象
       var playBtn = document.getElementsByClassName('idMusicPlayControll')[0];
       var Audio = document.getElementsByTagName('audio')[0];
       var Timebox = document.getElementsByTagName('all_time');
       var nowTime = document.getElementsByClassName('nowtime');
       var ProcessBar = document.getElementsByClassName('process_bar')[0];
       var Processed = ProcessBar.getElementsByTagName('p')[0];
       var musicList = eval("("+music+")");
       /**
        * 初始化当前播放的音频时间
        */
       Timebox.innerHTML = data_format(Audio.duration);
       
       /**
        *检测是否自动播放
        */
       if(Audio.play){

       	    playBtn.className = 'paused';
       	    setProcess();
            // Lyrics_init(); //初始化歌词
       }

      /**
       *  初始化音乐容器
       */
       function initMusic() {
            // 从列表中读取第一个
            var firid = musicList[0];
            var data = {id:firid};
            $.ajax({
                type:"GET",
                url:"/index/music-data",
                data:data,
                dataType:"Json",
                success:function (res) {
                     console.log(res);
                     reduner(res,1);
                }
            })
            // 并删除列表元素
            musicList.shift();
            var queue_list_box = document.getElementsByClassName('queue_list_box')[0];
            var queue_item = document.getElementsByClassName('queue_item')[0];
            queue_list_box.removeChild(queue_item);

            // 获取下一个音乐id 当前列表的最后一个id做为值传
            $nastId = musicList[musicList.length-1];
            ndata = {id:$nastId};
            $.ajax({
                type:"GET",
                url:"/index/next-music-info",
                data:ndata,
                dataType:"json",
                success:function (res) {
                    musicList.push(res[0]['id']);
                    console.log(musicList);
                    var queue_list_box = document.getElementsByClassName('queue_list_box')[0];
                    var _html = "<div class=\"queue_item\"><div class=\"queue_name\"><span class=\"songnum\"></span><span class=\"songname\">"+res[0]['m_name']+"</span></div><div class=\"queurinf\">"+res[0]['m_author']+"</div><div class=\" b m_up_play\"></div></div>";
                    console.log(_html);
                    queue_list_box.innerHTML += _html;
                    // 重新编排索引
                    var songnum = document.getElementsByClassName('songnum');
                    for (var i=0;i<songnum.length;i++){
                        songnum[i].innerHTML = i+1;
                    }
                }
            })
            Audio.play();
            setProcess();
       }

      /**
       * 重新渲染数据
       */
      function reduner(data,type) {
          if(type==1) {
              var name = document.getElementsByClassName('name')[0];
              var play_details = document.getElementsByClassName('play_details')[0];
              var playing_name = document.getElementsByClassName('playing_name')[0];
              Audio.src = data['m_path'];
              name.innerHTML = "歌名："+data['m_name'];
              play_details.innerHTML = data['m_author'];
              playing_name.innerHTML = data['m_name']+"<span class=\"playing\">正在播放</span>";
          }
      }

      /**
        * 暂停||播放
        */
       playBtn.onclick = function(){
       	    if(Audio.paused){
       	    	  this.className = 'paused';
       	    	  Audio.play();
       	    	  setProcess();
       	    }else{
                  Audio.pause();
       	    	  this.className = 'play';
       	    }
       }
       
        //歌曲播放进度函数
        function setProcess(){
                var Timer = null;
                Timer = setInterval(function(){
                	 if (Audio.ended) {
                	     clearInterval(Timer);
                         initMusic();
                	 }
                     var NowTime = data_format(Audio.currentTime);
                     nowTime[0].innerHTML = NowTime;
                     //计算比例值
                     var scale = Audio.currentTime/Audio.duration;
                     //计算机进度条实时宽度
                     var currentWidth = ProcessBar.offsetWidth *scale;

                     if (scale>0.9){

                         upshowNextTip();
                     }

                     Processed.style.width = currentWidth + 'px';
                     // Lyrics_synchronization(Audio.currentTime);

                },1000);
        }
        
        /**
         *歌曲进度调整 
         */
        ProcessBar.onclick = function(e){
        	 var event = window.event||e;
        	 var evClickpos = event.clientX;
        	 // 根据当前位置计算出比例
        	 var scale = evClickpos/ProcessBar.offsetWidth;
             var NowPosTime = Audio.duration*scale;
             Audio.currentTime = NowPosTime;
        	  Move(Processed,'width',evClickpos);
             Lyrics_synchronization(NowPosTime);
        }

        function upshowNextTip() {
             var timer1 = '';
             var m_up_play = document.getElementsByClassName('m_up_play')[0];
             var iNow = 0;
             timer1 = setInterval(function () {
                 if (iNow==10){
                       clearInterval(timer1);
                       return;
                 }
                 if (iNow%2==0){
                     m_up_play.style.display = 'none';
                 }else{
                     m_up_play.style.display = 'block';
                 }
                 iNow++;
             },1000)
        }

        //时间格式化函数
        function data_format(time){
                var h,s,m,remain;
                h= fill_zero(parseInt(time/3600));
                remain = time%3600;
                m = fill_zero(parseInt(remain/60));
                remain = fill_zero(parseInt(remain%60));
                s = remain;
                return m+":"+s;
        }

        //实现歌词滚动
        function Lyrics_synchronization(AudioTime){
                var Lrcbox = $('Lrc_show').getElementsByTagName('ul')[0];
                var list = Lrcbox.getElementsByTagName('li');
                for(var i=0; i<list.length;i++ ){
                      var start = list[i].getAttribute('time');
                      var end = list[i].getAttribute('endTime');
                      
                      if(AudioTime>=start && AudioTime<=end || i==list.length){
                              iTop = list[i].getAttribute('Top');
                              for(var j=0;j<list.length;j++){
                                      list[j].className = ''
                              }
                              //当前歌词颜色
                              list[i].className = 'Curren';
                              //滚动歌词到此次
                              Move(Lrcbox,'top',-iTop);
                      }
                }

        }

        //补零函数
        function fill_zero(num){
        	   if(num<=9){
                     
                     return "0"+num;

        	   }else{
        	   	     return ""+num;
        	   }
        }



        /**
         * 获得每个li的 Top 值 
         */
        function GetTop(LrcLi){
             for(var i=0;i<LrcLi.length;i++){
                   var Top = 0;
                   for(var j=0; j<i;j++){
                        Top+=LrcLi[j].offsetHeight;
                   }

                   LrcLi[i].setAttribute('top',Top);

                   if(i<LrcLi.length-1){
                        var nextStart = LrcLi[i+1].getAttribute('time');
                        LrcLi[i].setAttribute('endTime',nextStart);
                   }
                   
             }
        }

        /**
         * 歌词渲染函数
         */
        function Lyrics_init(){
              var LrcText = $('contentright').getElementsByTagName('input')[0].value;
              var Lrc = parseLyric(LrcText);
              var LrcUl = $('Lrc_show').getElementsByTagName('ul')[0];
              LrcUl.innerHTML = '';
              //将歌词填充到歌词域
              for(var i in Lrc){
                     var LrcTxte = Lrc[i];
                     var LrcLi = document.createElement('li');
                     LrcLi.setAttribute('time',i);
                     LrcLi.innerHTML = LrcTxte;
                     LrcUl.appendChild(LrcLi);
              }
              LrcLi = LrcUl.getElementsByTagName('li');
              GetTop(LrcLi);
        }
        
      //   /**
      //    * 歌词格式化函数
      //    * @param  {[type]} text 歌词文本
      //    * @return {[array]}      返回匹配后的歌词数组
      //    */
      //  function parseLyric(text) {
      //         lyric = text.split('\n'); //先按行分割
      //         var _l = lyric.length; //获取歌词行数
      //         lrc = new Array(); //新建一个数组存放最后结果
      //         for(i=0;i<_l;i++) {
      //             var d = lyric[i].match(/\[\d{2}:\d{2}((\.|\:)\d{2})\]/g);  //正则匹配播放时间
      //             var t = lyric[i].split(d); //以时间为分割点分割每行歌词，数组最后一个为歌词正文
      //             if(d != null) { //过滤掉空行等非歌词正文部分
      //                 //换算时间，保留<a href="https://www.baidu.com/s?wd=%E4%B8%A4%E4%BD%8D%E5%B0%8F%E6%95%B0&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YLujbYrHK-PHIWnvD1njmv0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EPWc1PHmznWT1n1bsnjmdPW0Y" target="_blank" class="baidu-highlight">两位小数</a>
      //                 var dt = String(d).split(':'); 
      //                 var _t = Math.round(parseInt(dt[0].split('[')[1])*60+parseFloat(dt[1].split(']')[0])*100)/100; 
      //                 lrc.push([_t, t[1]]);
      //             }
      //         return lrc;
      //       }
      // } 

      function parseLyric(lrc) {
            var lyrics = lrc.split("\n");
            var lrcObj = {};
            for(var i=0;i<lyrics.length;i++){
                var lyric = decodeURIComponent(lyrics[i]);
                var timeReg = /\[\d*:\d*((\.|\:)\d*)*\]/g;
                var timeRegExpArr = lyric.match(timeReg);
                if(!timeRegExpArr)continue;
                var clause = lyric.replace(timeReg,'');

                for(var k = 0,h = timeRegExpArr.length;k < h;k++) {
                    var t = timeRegExpArr[k];
                    var min = Number(String(t.match(/\[\d*/i)).slice(1)),
                        sec = Number(String(t.match(/\:\d*/i)).slice(1));
                    var time = min * 60 + sec;
                    lrcObj[time] = clause;
                }
            }
          return lrcObj;
       }
      
}